'use strict';

const { Service } = require('egg');
const https = require('https');

class CustomService extends Service {
  notify(touser, content, date) {
    const obj = {
      touser,
      msgtype: 'text',
      text: {
        content,
      },
    };
    const str = JSON.stringify(obj);
    const length = str.length;
    setTimeout(() => {
      console.log('Notice activated!');
      this.ctx.service.token.getToken().then(value => {
        const request = https.request('https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' + encodeURIComponent(value), {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Content-Length': length,
          },
        }, res => {
          console.log(res.statusCode);
          let data = '';
          res.on('data', chunk => { data += chunk; });
          res.on('end', () => {
            console.log(data);
            console.log('Notice ended!');
          });
        });
        request.write(str, error => {
          if (error) console.log(error);
        });
        request.end();
      });
    }, Number(date) - Number(new Date()));
    console.log('Notice set!');
  }
}

module.exports = CustomService;
